package edu.hunan.cxb18.service.impl;

import edu.hunan.cxb18.car.Car;
import edu.hunan.cxb18.car.CarItem;
import edu.hunan.cxb18.error.impl.UserException;
import edu.hunan.cxb18.mapper.AddressMapper;
import edu.hunan.cxb18.mapper.CategoryMapper;
import edu.hunan.cxb18.mapper.OrderMapper;
import edu.hunan.cxb18.mapper.OrderitemMapper;
import edu.hunan.cxb18.pojo.*;
import edu.hunan.cxb18.service.OrderService;
import edu.hunan.cxb18.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Service;

/**
 * @author AuthorName
 * @create 2020-06-11 1:11
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderitemMapper orderitemMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public String createOrder(User user, Car car) throws UserException {
        Order o=new Order();
        o.setTotal(car.getTotal());
        o.setQty(car.getItems().size());
        String oid = UUIDUtils.uuid();
        o.setId(oid);
        List<Orderitem> orderItems=new ArrayList<>();
        List<CarItem> carItems=car.getItems();
        orderMapper.insertSelective(o);
        for (int i = 0; i < carItems.size(); i++) {
            CarItem carItem=carItems.get(i);
            Orderitem orderItem = new Orderitem();
            orderItem.setPid(carItem.getGoods().getId());
            orderItem.setPname(carItem.getGoods().getPname());
            orderItem.setQty(carItem.getQty());
            orderItem.setPrice(carItem.getGoods().getMarketPrice());
            orderItem.setOid(oid);
            orderitemMapper.insertSelective(orderItem);
        }
        return oid;
    }

    @Override
    public Order queryByPidWithItems(String pidStr) throws UserException {
        return null;
    }

    @Override
    public void deleteOrderItem(Integer pid) throws UserException {

    }

    @Override
    public Order queryByOidWithItems(String oid) throws UserException {
        Order o = orderMapper.selectByPrimaryKey(oid);
        OrderitemExample orderitemExample = new OrderitemExample();
        OrderitemExample.Criteria criteria = orderitemExample.createCriteria();
        criteria.andOidEqualTo(oid);
        List<Orderitem> orderitems = orderitemMapper.selectByExample(orderitemExample);
        o.setOrderitem(orderitems);
        return o;
    }

    @Override
    public void payOrder(Address address) throws UserException {
        addressMapper.insertSelective(address);
    }

    @Override
    public void checkQty(String pidStr, Integer qty) throws UserException {

    }
}
